
import React, { useState, useEffect, useContext } from 'react';
import { useHistory, useRouteMatch } from "react-router-dom";
import { NavBar, Toast, List, InfiniteScroll, SwipeAction, Popup } from 'antd-mobile';
import { observer } from "mobx-react-lite";
import moment from 'moment';

import ChatInboxCard from '../../../components/ChatInboxCard';
import Collection from '../../../components/Collection';
import { resolveMsgFormContent } from '../../../utils/index';

import { MySdkStoreContext } from '../../../context';
import { ConversationType } from '../../../constants';

import './style.scss';

const ConverList = observer(() => {
  const history = useHistory();
  const { params: { groupId } } = useRouteMatch();
  const mySdkStore = useContext(MySdkStoreContext);
  const [pagination, setPagination] = useState({ pageIndex: 1, totalPage: 1 });
  const [converList, setConverList] = useState([]);
  const [groupName, setGroupName] = useState('');
  const [collectionCompProps, setCollectCompProps] = useState({ visible: false });
  const [topModeId, setTopModeId] = useState();
  const [topModeList, setTopModeList] = useState([]);

  // 获取分组列表
  useEffect(async () => {
    const groupList = await mySdkStore.sdk.queryConversationGroups()??[];
    const topModeId = groupList.find(item => item.groupName.indexOf('置顶') > -1)?.id;
    setTopModeId(topModeId);
    const groupItem = groupList.find(item => +item.id === +groupId);
    setGroupName(groupItem?.groupName);
  }, []);

  useEffect(async () => {
    getConver(1);
  }, []);

  useEffect(() => {
    // 重置收取消息回调
    mySdkStore.sdk.onNewMessage = (msgs) => {
      mySdkStore.onNewMessage(msgs);
      const lastMsg = msgs[msgs.length - 1];
      const { cid, msgType, msgContent, msgId, lastMsgRecallStatus, lastMsgSenderId } = lastMsg;
      setConverList((preConverList) => {
        const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
        if(matchIndex >= 0) {
          const lastMsg = lastMsgRecallStatus > 0 ? `${lastMsgSenderId === mySdkStore.mockConfig.userId ? '你' : '对方'}撤回了一条消息`: resolveMsgFormContent(msgType, msgContent);
          const matchItem = preConverList[matchIndex];
          const { unReadCount, bizParams } = matchItem;
          preConverList[matchIndex] = {
            ...matchItem,
            unReadCount: bizParams.is_default_read ? unReadCount : (unReadCount + msgs.length),
            lastMsgId: msgId,
            lastMsgContentType: msgType,
            lastMsg,
            gmtModified: new Date().valueOf(),
            bizParams: {...bizParams, is_hidden: '0' }
          };
          if (bizParams.is_hidden === '1') {
            mySdkStore.sdk.addConversationUserMark({ cid, marks: [{ propertyName: 'is_hidden', propertyValue: 0 }] });
          }
        }
        return [...preConverList];
      });
    };
    mySdkStore.sdk.onGroupInfoChange = (updateGroupRepones) => {
      const { cid, updateType, name, logoUrl } = updateGroupRepones
      setConverList((preConverList) => {
        const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
        if(matchIndex > -1){
          const matchItem = preConverList[matchIndex];
          if(updateType === 'name') {
            preConverList[matchIndex] = {...matchItem, name };
          } else if(updateType === 'logo') {
            preConverList[matchIndex] = { ...matchItem, logoUrl };
          }
        }
        return [...preConverList];
      });
    };

    return () => {
      mySdkStore.sdk.onNewMessage = mySdkStore.onNewMessage;
    }
  }, []);

  const conversationEdit = (action, converInfo) => {
    const { lastMsgId, cid, bizParams = {} } = converInfo;
    console.log('conversationEdit>>>', action, converInfo);
    const { val } = action;
    if(!mySdkStore.sdk) return;
    if(val === 'allRead') {
      //消息游标已读
      mySdkStore.sdk.changeMessagesStatus({type: 'read', cursorMsgId: lastMsgId, cid});
      setConverList((preConverList) => {
        const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
        if(matchIndex > -1) {
          const matchItem = preConverList[matchIndex]
          preConverList[matchIndex] = {...matchItem, unReadCount: 0 };
        }
        return [...preConverList];
      });
    }
    if(val === 'is_default_read') {
      //会话新消息默认已读
      const newDefaultReadState = !bizParams.is_default_read;
      mySdkStore.sdk.setConversationTag({ cid, type: 'is_default_read', value: newDefaultReadState });
      setConverList((preConverList) => {
        const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
        if(matchIndex > -1) {
          const matchItem = preConverList[matchIndex]
          const { bizParams = {} } = matchItem;
          preConverList[matchIndex] = {...matchItem, bizParams: { ...bizParams, is_default_read: newDefaultReadState } };
        }
        return [...preConverList];
      });
    }
  }

  const getConver = async (pageIndex = 1) => {
    return mySdkStore.sdk.queryConversationListByGroup({ pageIndex, pageSize: 10, groupId }).then(data => {
      const { totalPage, list } = data;
      setPagination({ pageIndex, totalPage });
      const newConvers = list.map(conver => {
        const { gmtCreate, lastMsgContentType, lastMsgContent, lastMsgSenderId, lastMsgRecallStatus } = conver;
        const lastMsg = lastMsgRecallStatus > 0 ? `${lastMsgSenderId === mySdkStore.mockConfig.userId ? '你' : '对方'}撤回了一条消息`: resolveMsgFormContent(lastMsgContentType, lastMsgContent);
        return { ...conver, gmtCreate: moment(gmtCreate).format('YYYY/MM/DD HH:mm:ss'), lastMsg }
      })

      setConverList(converList => {
        const newConverList = [...converList, ...newConvers];
        return newConverList;
      });
      Toast.clear();
    });
  }

  const getNextData = async () => {
    await getConver(pagination.pageIndex + 1);
  }

  const toChatPage = (cid) => history.push({pathname: `/chatDetail/${cid}`, search: `?debug=true` });

  const handleToggleToGroup = async (cid, rowData) => {
    if (!rowData.topMode) {
      // 置顶
      rowData.topMode = true;
      await mySdkStore.sdk.addConversationToGroups({ cid, groupId: topModeId });
      setConverList(converList => {
        return [rowData, ...converList.filter(item => item.cid !== cid)];
      });
      setTopModeList([...topModeList, rowData]);
    } else {
      // 取消置顶
      rowData.topMode = false;
      await mySdkStore.sdk.removeConversationFromGroups({ cid, groupId: topModeId });
      setConverList(converList => {
        return [...converList.filter(item => item.cid !== cid), rowData];
      });
      setTopModeList(converList => {
        return converList.filter(item => item.cid !== cid)
      });
    }
  }

  const handleRemoveConversation = async (cid) => {
    const res = await mySdkStore.sdk.addConversationUserMark({ cid, marks: [{ propertyName: 'is_hidden', propertyValue: 1 }] });
    if (res?.errorMessage) {
      Toast.show(res.errorMessage);
      return;
    }
    setConverList(converList => converList.filter(item => item.cid !== cid));
  }

  const handleCollectionOk = async (tagCodes, cid) => {
    try {
      await mySdkStore.sdk.collectSession({ cid, tagCodes });
      Toast.show('标记成功');
      setCollectCompProps({ visible: false });
    } catch(e) {
      console.log(e);
    }
  }

  const handleCollect = (cid) => {
    setCollectCompProps({
      visible: true,
      cid,
      onOk: (tagCode) => handleCollectionOk(tagCode, cid),
      onClose: () => setCollectCompProps({ visible: false }),
    });
  }

  const renderRow = (rowData) => {
    const { cid, bizParams = {} } = rowData;
    const { is_default_read } = bizParams;
    const collectAction = {
      key: 'collect',
      text: '收藏',
      color: 'warning',
      onClick: () => handleCollect(cid),
    };
    const stayTopAction = {
      key: 'stayTop',
      text: !rowData.topMode ? '置顶' : '取消置顶',
      color: 'primary',
      onClick: (e) => { e.stopPropagation(); handleToggleToGroup(rowData.cid, rowData) }
    };
    const deleteAction = {
      key: 'delete',
      text: '移除',
      color: 'danger',
      onClick: () => handleRemoveConversation(cid),
    };

    const rightActions = rowData.type === ConversationType.Notify ? [collectAction, stayTopAction] : [collectAction, stayTopAction, deleteAction];
    if (mySdkStore.isHideSomeFunctions) {
      rightActions.shift();
    }
    return (
      <SwipeAction
        rightActions={rightActions}
      >
        <ChatInboxCard
        key={cid}
        onCardClicked={() => toChatPage(cid)}
        {...rowData}
        isDefaultRead={is_default_read}
        editFunc={(action) => conversationEdit(action, rowData)}
        />
    </SwipeAction>
    )
  };

  return (<div className="conversationGroupListPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>{ groupName }</NavBar>
        <div className="converList">
        <List style={{ '--border-inner': 0, '--border-bottom': 0 }}>
          {converList.filter((item) => item.bizParams?.is_hidden !== '1').map(item => (
            <List.Item key={item.cid}>
              {renderRow(item)}
            </List.Item>
          ))}
          </List>
          <InfiniteScroll loadMore={getNextData} hasMore={pagination.totalPage > pagination.pageIndex}/>
        </div>
        <Popup visible={collectionCompProps.visible} destroyOnClose bodyClassName="selectorOperationsBarComponnet-collectionPopup">
          <Collection {...collectionCompProps} />
        </Popup>
    </div>)
})

export default ConverList;